package com.hz.friends.db;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DBContactUserManager {
	private DBHelper helper;
	private SQLiteDatabase db;
	private int pageSize = 30;

	public DBContactUserManager(Context context) {
		helper = new DBHelper(context);
		// 因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0,
		// mFactory);
		// 所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
		db = helper.getWritableDatabase();
	}

	/**
	 * 插入或者更新
	 * 
	 * @param user
	 */
	public void saveOrUpdate(DBContactUser user) {
		db.execSQL("REPLACE  INTO " + DBHelper.TABLE_CONTACTUSER
				+ " VALUES(?, ?, ?, ?,?)", new Object[] { user.getUserid(),
				user.getHeardurl(), user.getNickname(), user.getLastContent(),
				new Date().getTime() });

	}

	/**
	 * 删除联系人【删除前需删除对应联系人消息】
	 * @param id
	 */
	public void deleteUserById(String id) {
		db.execSQL("DELETE FROM " + DBHelper.TABLE_CONTACTUSER
				+ " WHERE userId='" + id + "'");
	}

      /**
       * 分页查询联系人列表
       * @param page
       * @return
       */
	public List<DBContactUser> queryUserList(int page) {
//		String ord = (sort==null|| sort.toLowerCase().startsWith("a"))?"asc":"desc";
		List<DBContactUser> userlist = new ArrayList<DBContactUser>();
		Cursor c = db.rawQuery("select * from " + DBHelper.TABLE_CONTACTUSER
				+ " order by time limit " + pageSize
				+ " offset " + page, null);
		while (c.moveToNext()) {
			DBContactUser user = new DBContactUser();
			user.setHeardurl(c.getString(c.getColumnIndex("heardUrl")));
			user.setLastContent(c.getString(c.getColumnIndex("lastContent")));
			user.setNickname(c.getString(c.getColumnIndex("nickName")));
			user.setTime(new Date(c.getLong(c.getColumnIndex("time"))));
			user.setUserid(c.getString(c.getColumnIndex("userId")));
			userlist.add(user);
		}
		c.close();
		return userlist;
	}

	public void closeDB() {
		db.close();
	}
}
